#!/usr/bin/env node
const Toolbox = require("./toolbox");
const path = require("path");
let ROOTPATH = "E:\\Syncthing-files\\NHBOOK";
// ROOTPATH = path.join(__dirname,"./test");
const fs = require("fs-extra");
const util = require("util");

Toolbox.safeListDir(ROOTPATH).then(async vals => {
  let target_to_be_deleted = [];
  for (let val of vals) {
    if (val.stats.isDirectory()) {
      let o_list = await Toolbox.safeListDir(val.full_path);
      if (o_list.filter(x => x.stats.isFile() && x.relative_path.endsWith("book.json")).length == 0) {
        target_to_be_deleted.push(val.full_path);
        console.log(val.relative_path, "没有book.json,需要删除")
      } else {
        console.log(val.relative_path, "有book.json,保留")
      }
    }
  }
  console.log("检测到",target_to_be_deleted.length,"个文件夹需要删除")
  for (let tgt of target_to_be_deleted) {
    try {
      await fs.rmdir(tgt,{recursive:true});
      console.log(`删除${tgt}OK`)
    } catch (e) {
      console.log(`删除${tgt}FAIL,${util.inspect(e)}`)
    }
  }
  console.log("\n\n END")
  process.exit(0);
})